package at.bartinger.gameoflive;

import android.graphics.Canvas;
import android.graphics.Color;
import android.util.Log;
import android.view.SurfaceHolder;

public class GameOfLiveThread extends Thread{



	private boolean mDone;
	private GameOfLiveRenderer mRenderer;
	private SurfaceHolder mSurfaceHolder =null;
	private GameOfLiveView view;
	private Canvas canvas;
	public boolean hasSurface = false;
	public boolean gameUpdates = false;

	public boolean[][] cells;

	public GameOfLiveThread(GameOfLiveView view, GameOfLiveRenderer renderer) {
		this.mRenderer = renderer;
		this.view = view;

		mSurfaceHolder = view.getSurfaceHolder();

		mDone = false;
		setName("Game Of Live Thread");

		cells = new boolean[renderer.rows][renderer.colums];
	}

	public void setCellsize(int cellsize){
		synchronized(cells){
			mRenderer.setCellsize(cellsize);
			boolean[][] temp = cells;
			cells = new boolean[mRenderer.rows][mRenderer.colums];
			int x = getMin(temp.length,cells.length);
			int y = getMin(temp[0].length,cells[0].length);
			for(int i =0; i < x; i++){
				for (int j = 0; j < y; j++) {
					cells[i][j] = temp[i][j];
				}
			}
		}
	}
	
	public void toogleInfo(){
		mRenderer.drawInfo = !mRenderer.drawInfo;
	}
	
	public GameOfLiveRenderer getRenderer(){
		return mRenderer;
	}

	@Override
	public void run() {
		while (!mDone) {

			synchronized (this) {
				if(!hasSurface) {
					while (!hasSurface) {
						try {
							wait();
						} catch (InterruptedException e) {}
					}
				}

				if (mDone) {
					break;
				}

			}


			synchronized(mSurfaceHolder){

				canvas = mSurfaceHolder.lockCanvas();

				if (canvas != null) {
					canvas.drawColor(Color.WHITE);
					if (gameUpdates){
						view.update();
					}

					mRenderer.drawFrame(canvas, cells);
					mSurfaceHolder.unlockCanvasAndPost(canvas);

				}else{
					Log.e("Game of Live", "Canvas are null");
				}
			}
		}
	}

	public void requestExitAndWait() {
		synchronized(this) {
			mDone = true;
			notify();
		}
		try {
			join();
		} catch (InterruptedException ex) {
			Thread.currentThread().interrupt();
		}
	}
	
	public void resetGeneration(){
		mRenderer.generation = 0;
	}

	public void surfaceCreated() {
		synchronized(this) {
			hasSurface = true;
			notify();
		}
	}


	public void surfaceDestroyed() {
		synchronized(this) {
			mDone = false;
			hasSurface = false;
			notify();
		}
	}

	private int getMin(int n1, int n2){
		if(n1 > n2) return n2;
		else return n1;
	}

}
